package com.whub507.msgmanager.sso.controller;

import com.whub507.msgmanager.sso.client.auth.AuthUtils;
import com.whub507.msgmanager.sso.client.sso.SSOService;
import com.whub507.msgmanager.sso.client.sso.SimpleClientHttpRequestFactory4Https;
import com.whub507.msgmanager.sso.context.ContextUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 应用首页，受保护资源
 * 
 * @author Admin
 *
 */
@RestController
@RequestMapping("/index2")
public class IndexController {

	/**
	 * 应用唯一标识,对应统一权限分系统中应用ID
	 */
	private String app_id = "app_demo_id";

	/**
	 * 应用秘钥，用于调用统一权限接口时按规范加密
	 */
	private String private_key = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAnBaXZM/bVKqNT301aln+ZlVYaCEtuwfz8Wcg60fO9V/UFVvbnYXTWxKWUaEtx5f8ThxjE66M6n4LQ3gb56P82wIDAQABAkEAi///Xp7I3VH0WV22sWNyuRrHpu5LdDwX42hasG3CBXa9nb832UQBLtZ2eYJNL2P+otIYmZ3ogMHld0PAFQfn4QIhAM56u9XMRpbqzx8GUMHJYgqrTJ89CdIYlU29V4FnFBOJAiEAwYX6eH47MU/fPcXCD2WRpOwRyCAGNpaZmVQFcrgz4EMCIDEMVrJi5CHVhX4JMgXWoMOIDZuGFF8kF9Nvtum2Yr6BAiBMI+OFLt0pLKy/yCPvHN4tzje8zmTDa4NpYTZ3iWPXswIgPogSl3HQja4ynZs0nP4snRTYa32bb3rQmgifXFLSxWg=";

	/**
	 * 应用公钥，在统一权限-应用管理中注册，调用统一权限接口时，后者使用公钥解密确认调用者身份可信
	 */
	private String public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJwWl2TP21SqjU99NWpZ/mZVWGghLbsH8/FnIOtHzvVf1BVb252F01sSllGhLceX/E4cYxOujOp+C0N4G+ej/NsCAwEAAQ==";

	@Autowired
	private SSOService ssoService;

	private RestTemplate restTemplate;

	/**
	 * 获取应用详情
	 */
	@Value("${drap_platform.sso_server.rootpath}/dpEntity/pt_app/{0}")
	private String getAppDetailUrl;

	@GetMapping
	public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 使用appsign调用统一权限管理接口获取应用详情
		Map app = getAppDetail();

		ContextUser user = (ContextUser) request.getSession().getAttribute("user");
		List menus = (List) request.getSession().getAttribute("menus");

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println("<html><body>");
		response.getWriter().println("<h1>应用详情</h1>");
		response.getWriter().println("<h3>" + app.toString() + "</h3>");

		response.getWriter().println("<h1>菜单</h1>");
		for (Iterator iterator = menus.iterator(); iterator.hasNext();) {
			Map menu = (Map) iterator.next();
			response.getWriter().println("<h3>" + menu.toString() + "</h3>");
		}

		response.getWriter().println("<h1>当前人</h1>");
		response.getWriter().println("<h3>ID:" + user.getUserID() + "</h3>");
		response.getWriter().println("<h3>LoginName:" + user.getUserLoginName() + "</h3>");
		response.getWriter().println("<h3>Name:" + user.getUserName() + "</h3>");
		response.getWriter().println("<h3>Email:" + user.getEmail() + "</h3>");
		response.getWriter().println("<h3>sso_token:" + user.getToken() + "</h3>");
		response.getWriter().println("<h3><a href='./logout'>Logout</a></h3>");
		response.getWriter().println("<body></html>");
	}

	@GetMapping("/api")
	public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.getWriter().println("Access api success.");
	}

	/**
	 * 调用统一权限分系统查询类接口示例：使用appsign方式，应用间也可采用此方式
	 * 
	 * 服务经过nginx代理后，后者默认不支持header含下划线名称
	 * 
	 * @throws Exception
	 */
	private Map getAppDetail() throws Exception {
		long time_stamp = System.currentTimeMillis();
		String plainText = app_id + time_stamp;
		String app_sign = AuthUtils.encrypt(private_key, plainText);

		// 调用规范：三项header必填
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.add("appid", app_id);
		requestHeaders.add("timestamp", String.valueOf(time_stamp));
		requestHeaders.add("appsign", app_sign);

		HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
		ResponseEntity<Map> response = restTemplate.exchange(MessageFormat.format(getAppDetailUrl, app_id),
				HttpMethod.GET, requestEntity, Map.class);
		return response.getBody();
	}

	@PostConstruct
	public void init() {
		SimpleClientHttpRequestFactory4Https requestFactory = new SimpleClientHttpRequestFactory4Https();

		requestFactory.setReadTimeout(120 * 1000);

		this.restTemplate = new RestTemplate(requestFactory);
	}

}
